package org.brownflat.lighthouse.monitoring.ci.pulse;

import org.brownflat.lighthouse.monitoring.ci.Build;
import org.brownflat.lighthouse.monitoring.ci.Builder;
import org.brownflat.lighthouse.monitoring.ci.Feed;
import org.brownflat.lighthouse.monitoring.xml.XMLDocument;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PulseBuilder implements Builder<Feed, String> {

    @Override
    public Feed build(String input) {
        XMLDocument document = new XMLDocument(input);
        Feed feed = new Feed();
        List<XMLDocument> builds = document.documentsAt("/rss/channel/item");

        Pattern pattern = Pattern.compile("Project (.*) (build \\d) (succeeded|failed)");

        for (Iterator iterator = builds.iterator(); iterator.hasNext(); ) {
            XMLDocument thisBuild = (XMLDocument) iterator.next();
            Build build = new Build();
            String title = thisBuild.selectValueAt("/item/title");
            build.setBroken(title.contains("failed"));
            Matcher matcher = pattern.matcher(title);
            if (matcher.matches()) {
                build.setProject(matcher.group(1));
            } else {
                throw new RuntimeException("Could not determine build name from " + title);
            }
            build.setDate(getDate(thisBuild.selectValueAt("/item/pubDate")));
            feed.addBuild(build);
        }

        return feed;
    }

    private Date getDate(String date) {
        try {
            return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z").parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
